package com.cgy.service.Impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.cgy.entity.Teacher;
import com.cgy.repository.TeacherRepository;
import com.cgy.service.TeacherService;
@Service
public class TeacherServiceImpl implements TeacherService {
@Autowired
private TeacherRepository teaRepository;

	@Override
	public Page<Teacher> findBytnamePage(Teacher t, Pageable pageable) {
		// TODO Auto-generated method stub
		return teaRepository.findAll(get(t), pageable);
	}

	private Specification<Teacher> get(Teacher t) {
		// TODO Auto-generated method stub
		return new Specification<Teacher>() {

			@Override
			public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.conjunction();//动态sql表达式
				List<Expression<Boolean>> exList = predicate.getExpressions(); 
				if(!StringUtils.isEmpty(t.getTname())) {
					exList.add(criteriaBuilder.like(root.get("tname"),"%"+t.getTname()+"%"));
				}
				/*
				 * if(t.getKeshi().getKid()!=null) {
				 * exList.add(criteriaBuilder.equal(root.get("keshi").get("kid"),t.getKeshi().
				 * getKid())); }
				 */
				return predicate;
			}
		};
	}
	@Transactional
	@Override
	public Teacher addAndUpdateTeacher(Teacher t) {
		// TODO Auto-generated method stub
		return teaRepository.saveAndFlush(t);
	}
	@Transactional
	@Override 
	public Integer deleteTeacher(Integer tid) {
		// TODO Auto-generated method stub
		return teaRepository.deleteTeacher(tid);
	}

	@Override
	public List<Teacher> findLikecard(Integer tcardid) {
		// TODO Auto-generated method stub
		return teaRepository.findLikecard(tcardid);
	}

	 

}
